<?php

header('Content-Type: text/plain; charset=utf-8'); 

// Load Google Maps GeoRSS feed
$georssurl = 'http://maps.google.com/maps/ms?ie=UTF8&msa=0&output=georss&msid=102125296625596679496.0004563675b2aac240bd5';

// retrieve search results
echo "Script last execution ".date('c')."\n\n";
echo "Downloading events list GeoRSS\n\n";
if($rss = simplexml_load_file($georssurl)) {
	// Monitor the items count in the geo rss feed
	$items_count = count($rss->channel->item);
	$last_items_count = file_exists('nbj_apns_last_count.txt') ? file_get_contents('nbj_apns_last_count.txt') : -1;
	$ret = file_put_contents('nbj_apns_last_count.txt', $items_count);
	echo "Events monitoring file write returned $ret\n\n";
	
	// As soon as the item count changes, grab the last item and push it
	if($items_count > 0 && ($_GET['force'] == 'true' || $last_items_count == -1 || (intval($items_count) != intval($last_items_count)))) {
		echo "Items count has changed : $items_count\nSending APNS push\n";
		$last_item = $rss->channel->item[$items_count - 1];
		
		preg_match("/^(.+)\\(Bar n°(\\d+).*\)$/", $last_item->title, $matches);
		$barnumber = intval($matches[2]);
		$barname = $last_item->title;
		$baraddress = preg_replace("/<(.|\\n)*?>/", " ", $last_item->description);
		$baraddress = preg_replace("/[\r\n\t]/", " ", $baraddress);
		$baraddress = trim($baraddress);
		
		define('APPKEY','APPKEY');
		define('PUSHSECRET', 'PUSHSECRET');
		define('PUSHURL', 'https://go.urbanairship.com/api/push/broadcast/');

		// Broadcast this message
		$contents = array();
		$contents['badge'] = $barnumber;
		$contents['alert'] = html_entity_decode("&#xE047; Bar de la semaine &#xE047;\n$barname\n$baraddress", ENT_COMPAT, "UTF-8");
		$contents['sound'] = "default";

		$push = array("aps" => $contents);
		$json = json_encode($push);
		echo "Sending JSON payload : $json";

		$session = curl_init(PUSHURL);
		curl_setopt($session, CURLOPT_USERPWD, APPKEY . ':' . PUSHSECRET);
		curl_setopt($session, CURLOPT_POST, True);
		curl_setopt($session, CURLOPT_POSTFIELDS, $json);
		curl_setopt($session, CURLOPT_HEADER, False);
		curl_setopt($session, CURLOPT_RETURNTRANSFER, True);
		curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
		curl_exec($session); 

		// Check if any error occured
		$response = curl_getinfo($session);
		if($response['http_code'] != 200) {
		    echo "Got negative response from server, http code: ". $response['http_code'] . "\n";
		} else {
		    echo "Yah, it worked!\n";
		}
		curl_close($session);
	} else {
		echo "Items count has NOT changed : $items_count\n"; 
	}
}

?>